package com.qkjia.srb.sms.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.qkjia.common.exception.Assert;
import com.qkjia.common.exception.BusinessException;
import com.qkjia.common.result.ResponseEnum;
import com.qkjia.srb.sms.service.SmsService;
import com.qkjia.srb.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 *  @author 赵乾坤
 *  @since 2021-11-07 20:33
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Resource
    private JavaMailSender javaMailSender;


    /**
     * 发短信
     * @param mobile  手机号
     * @param templateCode 模板吗
     * @param param 验证码
     */
    @Override
    public void send(String mobile, String templateCode, HashMap<String, Object> param) {
        // 创建远程连接客户端对象
        DefaultProfile profile = DefaultProfile.getProfile(
        SmsProperties.REGION_Id,
        SmsProperties.KEY_ID,
        SmsProperties.KEY_SECRET);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        // 创建远程连接的请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", SmsProperties.REGION_Id);
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", SmsProperties.SIGN_NAME);
        request.putQueryParameter("TemplateCode", templateCode);

        // 把请求参数 gson化
        Gson gson = new Gson();
        String json = gson.toJson(param);
        request.putQueryParameter("TemplateParam",json);

        try {
            //使用客户端对象携带请求对象发送请求并得到响应结果
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            //ALIYUN_RESPONSE_FAIL(-501, "阿里云响应失败"),
            Assert.isTrue(success,ResponseEnum.ALIYUN_RESPONSE_FAIL);

            // 从响应结果获取数据
            String data = response.getData();
            // json序列号对象转化为类对象
            HashMap<String,String> resultMap = gson.fromJson(data, HashMap.class);
            String code = resultMap.get("Code");
            String message = resultMap.get("Message");
            log.info("阿里云短信发送响应结果：");
            log.info("code：" + code);
            log.info("message：" + message);

            //ALIYUN_SMS_LIMIT_CONTROL_ERROR(-502, "短信发送过于频繁"),//业务限流
            Assert.notEquals("isv.BUSINESS_LIMIT_CONTROL", code, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
            //ALIYUN_SMS_ERROR(-503, "短信发送失败"),//其他失败
            Assert.equals("OK", code, ResponseEnum.ALIYUN_SMS_ERROR);
        } catch (ServerException e) {
            log.error("阿里云短信发送SDK调用失败：");
            log.error("ErrorCode=" + e.getErrCode());
            log.error("ErrorMessage=" + e.getErrMsg());
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR , e);
        } catch (ClientException e) {
            log.error("阿里云短信发送SDK调用失败：");
            log.error("ErrorCode=" + e.getErrCode());
            log.error("ErrorMessage=" + e.getErrMsg());
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR , e);
        }
    }

    /**
     * 发邮箱验证码
     * @param addressee 邮箱号
     * @param param 验证码参数
     */
    @Override
    public void sendMail(String addressee, Map<String, Object> param) {
        log.info("开始发送邮件");
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            // 设置邮件标题
            message.setSubject("test");
            // 设置发件人邮箱地址
            message.setFrom("13583815554@qq.com");
            //设置收件人邮箱地址
            message.setTo(addressee);
            // 设置内容
            message.setText("验证码"+param.get("code"));
            javaMailSender.send(message);
            log.info("邮件发送成功");
        }catch (Exception e){
            log.error("邮件发送失败！！！");
            throw new BusinessException(ResponseEnum.ALIYUN_Mail_ERROR , e);
        }

    }
}